package com.powerunion.datacollection.web.struts;

import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.powerunion.datacollection.model.Accessories;
import com.powerunion.datacollection.model.ItemInfo;
import com.powerunion.datacollection.model.query.DataCollectionFormQuery;
import com.powerunion.datacollection.service.AccessoriesManager;
import com.powerunion.datacollection.service.DataCollectionFormManager;
import com.powerunion.datacollection.service.GlobalTargetsDataManager;
import com.powerunion.datacollection.service.ItemManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.log.LogHelper;

public class DataCollectionFormAction extends DispatchAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(
			DataCollectionFormAction.class);
	private DataCollectionFormManager dcfManager = null;

	public DataCollectionFormAction() {
		super();
		this.dcfManager = new DataCollectionFormManager();
	}

	public void finalize() throws Throwable {
		this.dcfManager = null;
		super.finalize();
	} 

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String saveStr = request.getParameter("formData");
		String itemTypeStr = request.getParameter("itemType");
		int itemType = 0;
		if(!StringUtils.isEmpty(itemTypeStr)){
			itemType = Integer.parseInt(itemTypeStr);
		}
		
		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();
			logger.debug("表单信息定义:" + saveStr);

			String currentUser = request.getRemoteUser();

			ItemManager itemManager = new ItemManager();
			String id = itemManager.save(saveStr, currentUser, itemType);
			
			if (id != null && !id.equals("")) {
				response.getWriter().write("{success:true,data:'" + id + "'}");
			} else {
				response.getWriter().write("{failure:true}");
			}

			transaction.commit();
		} catch (Exception e) {
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}

		return null;
	}

	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String currentUser = request.getRemoteUser();
		System.out.println("currentUser:"+currentUser);
		String categoryId = request.getParameter("id");
		DataCollectionFormQuery query = new DataCollectionFormQuery();
		query.setCategoryId(categoryId);

		String startStr = request.getParameter("start") == null ? "0" : request
				.getParameter("start");
		String limitStr = request.getParameter("limit") == null ? "28"
				: request.getParameter("limit");

		int start = Integer.parseInt(startStr);
		int limit = Integer.parseInt(limitStr);

		String result = this.dcfManager.getDataCollectionForms(query, start,
				limit);
		logger.debug("dataCollectionForms:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	public ActionForward showTemplate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String fsetId = request.getParameter("fsetId");
		request.setAttribute("fsetId", fsetId);
		
		String reType = request.getParameter("reType");
		request.setAttribute("reType", reType);
		
		String procId = request.getParameter("procId");
		request.setAttribute("procId", procId);
		
		String actId = request.getParameter("actId");
		request.setAttribute("actId", actId);
		
		String state = request.getParameter("state");
		request.setAttribute("state", state);
		
		String swId = request.getParameter("swId");
		request.setAttribute("swId", swId);
		
		String userCode = request.getRemoteUser();
		request.setAttribute("userCode", userCode);
		
		ItemManager itemManager = new ItemManager();
		ItemInfo item = itemManager.findByKey(fsetId);
		int type = item.getItemType();
		if(type == 20){//主从表类型
			return mapping.findForward("mainSubFormTemplate.view");
		}else{//指标类型
			request.setAttribute("itemplate", String.valueOf(0));
			GlobalTargetsDataManager gtdm = new GlobalTargetsDataManager();
			int permissionUPFile = gtdm.getPermissionUPFile(fsetId);
			request.setAttribute("permissionUPFile", String.valueOf(permissionUPFile));
			
			return mapping.findForward("template.view");
		}
		
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String[] ids = StringUtils.split(request.getParameter("codes"), ",");

		Transaction transaction = null;

		response.setContentType("text/json;charset=utf-8");
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			boolean flag = this.dcfManager.delete(ids);

			if (flag == true) {
				response.getWriter().print("{success:true}");
			} else {
				response.getWriter().write("{failure:true}");
			}
			transaction.commit();
		} catch (Exception e) {
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		return null;
	}

	public ActionForward loadInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String id = request.getParameter("id");
		response.setContentType("text/json;charset=utf-8");
		String data = this.dcfManager.loadInfo(id);
		logger.debug("loadInfo the DataCollectionForm:" + data);
		response.getWriter().print(data);
		return null;
	}
	
	public ActionForward loadAccessoriesInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String id = request.getParameter("id");
		Accessories as = new Accessories();
		AccessoriesManager am = new AccessoriesManager();
		as = am.findAccessoriesByKey(id);
		try{
			this.downloadAttach(response, as);
			
		}catch(Exception e){
			logger.error("", e);
			response.getWriter().write("{failure:true'}");
		}
		return null;
	}
	
    private void downloadAttach(HttpServletResponse response, Accessories file) {
		try {
	    	response.setContentType("APPLICATION/OCTET-STREAM;charset=utf-8");
	    	String nameStr = file.getFilename();
			response.setHeader("Content-Disposition","attachment; filename=\"" + new String(nameStr.getBytes(), "iso8859-1") + "\"");
			InputStream ins = file.getFileContent();
			ServletOutputStream stream = response.getOutputStream();
			int len;
			logger.debug("ins.available():"+ins.available());
			byte[] b = new byte[ins.available()]; 
			while ((len=ins.read(b)) != -1) {
				stream.write(b, 0, len);
				stream.flush();
			}
			ins.close();
			stream.close();
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    }
    
	public ActionForward uploadFiles(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String formId = request.getParameter("formId");
		AccessoriesManager am = new AccessoriesManager();
		String result = am.getAccessoriesByFormId(formId);
		logger.debug("uploadFiles:"+result);
		response.setContentType("text/json;charset=utf-8");
		try{
			response.getWriter().print(result);
		}catch(Exception e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
    
}
